package com.xx.jfb.tomcat_1;

import com.xx.jfb.server.Factory;
import com.xx.jfb.server.XXRequest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class MiniTomcat_1 {
    private ServerSocketChannel ssc;
    public  volatile int  threadNumber = 0;
    public Factory factory;
    public void setFactory(Factory factory) {
        this.factory = factory;
    }
    public void 开始(Integer port) throws IOException {
        try {
            ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ServerSocket serverSocket = ssc.socket();
            serverSocket.bind(new InetSocketAddress(port));
        }catch (SocketException e){
            throw new SocketException("create socket is error !");
        }catch (IOException e){
            throw new SocketException("io is error !");
        }

        while (true){
            try{
                //获得请求
                SocketChannel channel = ssc.accept();
                //新建线程处理请求
                if(null != channel){
                    server(channel);
                }
            }catch (Exception e){
                throw new IOException(" accept is error !");
            }
        }
    }

    public void server(SocketChannel channel ){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    buffer.flip();
                    String req = "";
                    while (buffer.hasRemaining()){
                        char b = (char)(buffer.get());
                        String s = String.valueOf(b);
                        req +=s;
                    }
                    System.out.println(req);
                    ByteBuffer reBuffer = ByteBuffer.allocate(1024);
                    //添加的响应头
                    String response = "";
                    //添加的响应头
                    response+="HTTP/1.1\n";
                    response+="Access-Control-Allow-Origin:*\n";
                    response += "Content-type:application/json\n\n";

                    String result = factory.callback(new XXRequest().build(req));
                    response += result;
                    reBuffer.put(response.getBytes(StandardCharsets.UTF_8));
                    reBuffer.flip();
                    channel.write(reBuffer);
                    channel.close();
                }catch (Exception e){

                }
            }
        }).start();
    }
}
